// 实现一个LazyMan，可以按照以下方式调用:
// LazyMan(“Hank”)输出:
// Hi! This is Hank!

// LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
// Hi! This is Hank!
// //等待10秒..
// Wake up after 10
// Eat dinner~

// LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
// Hi This is Hank!
// Eat dinner~
// Eat supper~

// LazyMan(“Hank”).eat(“supper”).sleepFirst(5)输出
// //等待5秒
// Wake up after 5
// Hi This is Hank!
// Eat supper

class LazyMan {
    constructor(name) {
        this.name = name
        this.tasks = []
        setTimeout(() => {
            this.next()
        }, 0);
    }

    next() {
        let task = this.tasks.shift()
        task && task()
    }
    eat(food) {
        let task = () => {
            console.log(`eat ${food}`)
            this.next()
        }
        this.tasks.push(task)

        return this
    }

    sleep(time) {
        let task = () => {
            setTimeout(() => {
                console.log("等待", time, "秒");
                this.next()
            }, time);

        }
        this.tasks.push(task)
        return this
    }

    // 首先睡觉
    sleepFirst(time) {
        this._sleepWrapper(time, true);
        return this;
    }
    _sleepWrapper(time, first) {
        const task = () => {
            setTimeout(() => {
                console.log(`Wake up after ${time}`);
                this.next();
            }, time * 1000);
        };
        if (first) {
            this.tasks.unshift(task); // 放到任务队列顶部
        } else {
            this.tasks.push(task); // 放到任务队列尾部
        }
    }
}

let lazyMan = new LazyMan('李兵')
lazyMan.eat("香蕉").sleep(10).eat('苹果')